<!--店铺管理-->
<script setup lang="ts">
import {AxiosPromise} from "axios";

defineOptions({
  name: "Store",
  inheritAttrs: false,
});

import {
	getStorePage,
	getStoreForm,
	saveStore,
	deleteStores,
	disableStores,
	enableStores,
	exportStore,
	importStore
} from "@/api/store";

import { StoreQuery, StoreForm } from "@/api/store/types";
import { CompanyForm } from "@/api/company/types";
import {getDictOptions} from "@/api/dict";
import {getCompanyList} from "@/api/company";
import moment from "moment";
import { ElLoading, UploadFile } from "element-plus";
import { importXhsBill } from "@/api/xhsBill";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<StoreQuery>({
  pageNum: 1,
  pageSize: 20,
});

const storeList = ref<[]>();
const storeDictList = ref<OptionType[]>();
const companyList = ref<CompanyForm[]>();

const dialog = reactive<DialogOption>({
  visible: false,
});
const importDialog = reactive<DialogOption>({
	title: "店铺数据导入",
	visible: false,
});

const excelFile = ref<File>();
const excelFilelist = ref<File[]>([]);
const formData = reactive<StoreForm>({});

const rules = reactive({
  commercePlatformStoreCode: [{ required: true, message: "请输入电商平台店铺编码", trigger: "blur" }],
  commercePlatformStoreName: [{ required: true, message: "请输入电商平台店铺名称", trigger: "blur" }],
  storeKey: [{ required: true, message: "请选择店铺平台", trigger: "change" }],
  companyCode: [{ required: true, message: "请选择入账主体", trigger: "change" }],
  billSystemStoreCode: [{ required: true, message: "请输入对账系统店铺编码", trigger: "blur" }],
  billSystemStoreName: [{ required: true, message: "请输入对账系统店铺名称", trigger: "blur" }],
});

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  getStorePage(queryParams)
    .then(({ data }) => {
      storeList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开字典类型表单弹窗
 *
 * @param dicTypeId 字典类型ID
 */
function openDialog(dicTypeId?: number) {
  getAllCompanyList()
  dialog.visible = true;
  if (dicTypeId) {
    dialog.title = "修改店铺";
    getStoreForm(dicTypeId).then(({ data }) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增店铺";
    formData.billSystemStoreCode = 'SHOP'+moment().format('YYMMDDHHmmSS')
  }
}

/**
 * 字典类型表单提交
 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
		saveStore(formData)
		  .then(() => {
			ElMessage.success("保存成功");
			closeDialog();
			handleQuery();
		  })
		  .finally(() => (loading.value = false));
	}
  });
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
}

/**
 * 删除字典类型
 */
function handleDelete(dictTypeId?: number) {
  const dictTypeIds = [dictTypeId || ids.value].join(",");
  if (!dictTypeIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteStores(dictTypeIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

const dictDataDialog = reactive<DialogOption>({
  visible: false,
});

/**
 * 获取字典类型的数据项
 *
 * @param typeCode 字典类型编码
 */
function getDictOptionList() {
	getDictOptions('platform').then((response) => {
		storeDictList.value = response.data;
	});
}

/**
 * 获取入账主体列表
 *
 */
function getAllCompanyList() {
  getCompanyList().then((response) => {
    companyList.value = response.data;
  });
}

function getDictName(key?: string) {
	if (storeDictList != undefined) {
		if (storeDictList.value != undefined) {
			for (let dict of storeDictList.value) {
				if (dict != undefined && dict.value+'' == key) {
					return dict.label
				}
			}
		}
	}
	return ''
}

function enabled() {
	const dictTypeIds = ids.value.join(",");
	if (!dictTypeIds) {
		ElMessage.warning("请勾选店铺");
		return;
	}

	enableStores(dictTypeIds).then(() => {
		ElMessage.success("启用成功");
		handleQuery();
	});
}

function disabled() {
	const dictTypeIds = ids.value.join(",");
	if (!dictTypeIds) {
		ElMessage.warning("请勾选店铺");
		return;
	}

	disableStores(dictTypeIds).then(() => {
		ElMessage.success("禁用成功");
		handleQuery();
	});
}

	/**
	 * Excel文件change事件
	 *
	 * @param file
	 */
	function handleExcelChange(file: UploadFile) {
		if (file.size !== undefined) {
			if (file.size > 20 * 1024 * 1024) {
				ElMessage.warning("上传文件大小已经超过20M，请尝试拆分成多个文件再上传");
				return false
			}
		}
		if (!/\.(csv|xlsx|xls|XLSX|XLS|CSV)$/.test(file.name)) {
			ElMessage.warning("上传Excel只能为xlsx、xls、csv格式");
			excelFile.value = undefined;
			excelFilelist.value = [];
			return false;
		}
		excelFile.value = file.raw;
	}

	/** 导入提交 */
	function handleImport() {
		if (!excelFile.value) {
			ElMessage.warning("上传Excel文件不能为空");
			return false;
		}
		const importLoading = ElLoading.service({
			lock: true,
			text: '导入中...',
			background: 'rgba(0, 0, 0, 0.7)',
		})
		importStore(excelFile.value).then((response) => {
			closeImportDialog();
			ElMessage.success('导入成功');
			resetQuery();
		}).finally(() => importLoading.close());
}

/**  关闭导入弹窗 */
function closeImportDialog() {
	importDialog.visible = false;
	excelFile.value = undefined;
	excelFilelist.value = [];
}

/** 导出小红书订单销售 */
function handleExport() {
	const strIds = [ids.value].join(",");
	exportStore(strIds).then((response: any) => {
		const blob = new Blob([response.data], {
			type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
		});
		const a = document.createElement("a");
		const href = window.URL.createObjectURL(blob); // 下载的链接
		a.href = href;
		a.download = decodeURI(
			response.headers["content-disposition"].split(";")[1].split("=")[1]
		); // 获取后台设置的文件名称
		document.body.appendChild(a);
		a.click(); // 点击导出
		document.body.removeChild(a); // 下载完成移除元素
		window.URL.revokeObjectURL(href); // 释放掉blob对象
	});
}

/** 打开导入弹窗 */
async function openImportDialog() {
	importDialog.visible = true;
}

onMounted(() => {
  handleQuery();
  getDictOptionList();
  getAllCompanyList()
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="店铺名称" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="店铺名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
				<div class="flex justify-between">
					<div>
						<el-button
							v-hasPerm="['sys:store:save']"
							type="success"
							@click="openDialog()"
							><i-ep-plus />新增</el-button
						>
						<el-button
							type="danger"
							:disabled="ids.length === 0"
							@click="handleDelete()"
							v-hasPerm="['sys:store:delete']"
							><i-ep-delete />删除</el-button
						>
						<el-button
							type="danger"
							:disabled="ids.length === 0"
							@click="enabled()"
							>启用</el-button
						>
						<el-button
							type="danger"
							:disabled="ids.length === 0"
							@click="disabled()"
							>禁用</el-button
						>
					</div>
					<div>
						<el-button class="ml-3" @click="openImportDialog" v-hasPerm="['sys:store:import']"
						><template #icon><i-ep-top /></template>导入</el-button
						>
						<el-button class="ml-3" @click="handleExport" v-hasPerm="['sys:store:export']"
						><template #icon><i-ep-download /></template>导出</el-button
						>
					</div>
				</div>
      </template>
      <el-table
        size="small"
        :header-row-style="{color: 'dimgray'}"
        v-loading="loading"
        highlight-current-row
        :data="storeList"
        border
				:height="storeList && storeList.length > 0 ? 570 : 130"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column label="电商平台店铺编码" prop="commercePlatformStoreCode" show-overflow-tooltip width="140"/>
        <el-table-column label="电商平台店铺名称" prop="commercePlatformStoreName" show-overflow-tooltip width="140"/>
        <el-table-column label="入账主体名称" show-overflow-tooltip width="150" prop="companyName"/>
        <el-table-column label="隶属平台" show-overflow-tooltip width="96" prop="platformName"/>
				<el-table-column label="状态" prop="statusName" show-overflow-tooltip width="80"/>
        <el-table-column label="财务系统店铺编码" prop="financeSystemStoreCode" show-overflow-tooltip width="100"/>
        <el-table-column label="财务系统店铺名称" prop="financeSystemStoreName" show-overflow-tooltip width="100"/>
        <el-table-column label="财务系统线下店铺编码" prop="financeOutlineStoreCode" show-overflow-tooltip width="100"/>
        <el-table-column label="财务系统线下店铺名称" prop="financeOutlineStoreName" show-overflow-tooltip width="100"/>
        <el-table-column label="对账系统店铺编码" prop="billSystemStoreCode" show-overflow-tooltip width="100"/>
        <el-table-column label="对账系统店铺名称" prop="billSystemStoreName" show-overflow-tooltip width="100"/>
        <el-table-column label="内部系统店铺编码" prop="innerSystemStoreCode" show-overflow-tooltip width="100"/>
        <el-table-column label="内部系统店铺名称" prop="innerSystemStoreName" show-overflow-tooltip width="100"/>
        <el-table-column label="内部系统线下店铺编码" prop="innerOutlineStoreCode" show-overflow-tooltip width="100"/>
        <el-table-column label="内部系统线下店铺名称" prop="innerOutlineStoreName" show-overflow-tooltip width="100"/>
        <el-table-column fixed="right" label="操作" width="130" align="center">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:store:save']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(scope.row.id)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              v-hasPerm="['sys:store:delete']"
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
	  :close-on-click-modal="false"
      @close="closeDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="160px"
      >
        <el-tabs type="border-card">
          <el-tab-pane label="对账系统" value="bill">
            <el-form-item label="隶属平台" prop="storeKey">
              <dictionary v-model="formData.storeKey" type-code="platform" clearable/>
            </el-form-item>
            <el-form-item label="入账主体" prop="companyCode">
              <el-select class="yz-el-select" v-model="formData.companyCode" placeholder="请选择">
                <el-option
                        v-for="item in companyList"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="对账系统店铺编码" prop="billSystemStoreCode">
              <el-input v-model="formData.billSystemStoreCode" placeholder="请输入对账系统店铺编码" disabled/>
            </el-form-item>
            <el-form-item label="对账系统店铺名称" prop="billSystemStoreName">
              <el-input v-model="formData.billSystemStoreName" placeholder="请输入对账系统店铺名称" clearable/>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="电商平台" value="commerce">
            <el-form-item label="电商平台店铺编码" prop="commercePlatformStoreCode">
              <el-input v-model="formData.commercePlatformStoreCode" placeholder="请输入电商平台店铺编码" clearable/>
            </el-form-item>
            <el-form-item label="电商平台店铺名称" prop="commercePlatformStoreName">
              <el-input v-model="formData.commercePlatformStoreName" placeholder="请输入电商平台店铺名称" clearable/>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="财务" value="finance">
            <el-form-item label="财务系统店铺编码" prop="financeSystemStoreCode">
              <el-input v-model="formData.financeSystemStoreCode" placeholder="请输入财务系统店铺编码" clearable/>
            </el-form-item>
            <el-form-item label="财务系统店铺名称" prop="financeSystemStoreName">
              <el-input v-model="formData.financeSystemStoreName" placeholder="请输入财务系统店铺名称" clearable/>
            </el-form-item>
            <el-form-item label="财务系统线下店铺编码" prop="financeOutlineStoreCode">
              <el-input v-model="formData.financeOutlineStoreCode" placeholder="请输入财务系统线下店铺编码" clearable/>
            </el-form-item>
            <el-form-item label="财务系统线下店铺名称" prop="financeOutlineStoreName">
              <el-input v-model="formData.financeOutlineStoreName" placeholder="请输入财务系统线下店铺名称" clearable/>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="内部系统" value="inner">
            <el-form-item label="内部系统店铺编码" prop="innerSystemStoreCode">
              <el-input v-model="formData.innerSystemStoreCode" placeholder="请输入内部系统店铺编码" clearable/>
            </el-form-item>
            <el-form-item label="内部系统店铺名称" prop="innerSystemStoreName">
              <el-input v-model="formData.innerSystemStoreName" placeholder="请输入内部系统店铺名称" clearable/>
            </el-form-item>
            <el-form-item label="内部系统线下店铺编码" prop="innerOutlineStoreCode">
              <el-input v-model="formData.innerOutlineStoreCode" placeholder="请输入内部系统线下店铺编码" clearable/>
            </el-form-item>
            <el-form-item label="内部系统线下店铺名称" prop="innerOutlineStoreName">
              <el-input v-model="formData.innerOutlineStoreName" placeholder="请输入内部系统线下店铺名称" clearable/>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

		<!-- 导入弹窗 -->
		<el-dialog
			v-model="importDialog.visible"
			:title="importDialog.title"
			width="600px"
			append-to-body
			@close="closeImportDialog"
		>
			<el-form label-width="80px">
				<el-form-item label="Excel">
					<el-upload
						class="upload-demo"
						action=""
						drag
						:auto-upload="false"
						accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
						:file-list="excelFilelist"
						:on-change="handleExcelChange"
						:limit="1"
					>
						<el-icon class="el-icon--upload">
							<i-ep-upload-filled/>
						</el-icon>
						<div class="el-upload__text">
							将文件拖到此处，或
							<em>点击上传</em>
						</div>
						<template #tip>
							<div class="el-upload__tip">xls/xlsx/csv files</div>
						</template>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleImport">确 定</el-button>
					<el-button @click="closeImportDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>
  </div>
</template>
